<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
      @returnBack="$emit('returnModify')"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('basic_information') }}</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :label-width="formInfo.labelWidth"
            :rules="formInfo.rules"
          ></page-form>
        </div>
        <div class="model-panel-title">
          <p>上架规则</p>
        </div>
        <div class="model-panel-body">
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ruleRef"
            :data="formInfo.data"
            :field-list="formInfo.ruleFieldList"
            :label-width="formInfo.labelWidth"
            :rules="formInfo.rules"
          />
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t('detailInfo') }}</p>
        </div>
        <div class="model-panel-body">
          <div class="layui-card-body fullBox table-height">
            <!-- 条件栏 -->
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-removeProduct>
                <el-button
                  :disabled="!canRemoveProduct"
                  @click="removeProduct()"
                  >删除产品</el-button
                >
              </template>
            </page-filter>
            <div class="flex_full_item">
              <!-- 表格 -->
              <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :api="tableInfo.api"
                  :pager="false"
                  :checkBox="true"
                  :isRowClickSelect="true"
                  v-model:query="filterInfo.query"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :tab-index="true"
                  :isDynamic="true"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-capacity="scope">
                    <el-form-item
                      v-if="scope.$index >= 0"
                      :prop="`data.${scope.$index}[capacity]`"
                      @click.stop.native=""
                    >
                      <el-input-number
                        v-model.number="scope.row.capacity"
                        style="width: 100%"
                        controls-position="right"
                        :min="0"
                        :max="99999"
                      />
                    </el-form-item>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <select-product
      v-if="productInfo.visible"
      v-model:show-dialog="productInfo.visible"
      v-model:query="productInfo.query"
      @callback="_selectProduct"
    />
  </div>
</template>

<script setup name="depotProductDetailManage">
import {
  getGoodsLocationById,
  creatGoodsLocation,
  updateGoodsLocation,
  getGoodsLocationProductRelation,
  quickCreateGoodsLocation,
} from '@/api/wms.js'
import SelectProduct from './selectProduct'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps([
  'visible',
  'title',
  'orderId',
  'modifyType',
  'params',
])

// 过滤相关配置
const filterInfo = ref({
  query: {
    goodsLocationId: props.orderId,
  },
  list: [
    { type: 'button', label: '添加产品', event: addProduct },
    { type: 'slot', value: 'removeProduct' },
  ],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [
    { label: '名称', value: 'commonName' },
    { label: '编码', value: 'productCode', minWidth: 80 },
    {
      label: '规格',
      value: 'standard',
      minWidth: 100,
    },
    {
      label: '单位',
      value: 'unitName',
      minWidth: 80,
    },
    {
      label: '厂家',
      value: 'brandName',
    },
    {
      label: '条码类型',
      value: 'codeTypeValue',
    },
    {
      label: '产品分类',
      value: 'productCategoryValue',
      minWidth: 80,
    },
    {
      label: '容量',
      value: 'capacity',
      type: 'slot',
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        show: true,
      },
    ],
  },
})

// 表单相关
const formInfo = ref({
  ref: null,
  ruleRef: null,
  data: {
    depotName: '',
    depotId: '',
    isConsignProductMixing:
      proxy.$store.state.permission.systemConfig.is_consign_product_mixing,
    isConsignBatchExpiryDateMixing:
      proxy.$store.state.permission.systemConfig
        .is_consign_batch_expiry_date_mixing,
    isConsignSupplierMixing:
      proxy.$store.state.permission.systemConfig.is_consign_supplier_mixing,
    isNotConsignProductMixing:
      proxy.$store.state.permission.systemConfig.is_not_consign_product_mixing,
    isNotConsignBatchExpiryDateMixing:
      proxy.$store.state.permission.systemConfig
        .is_not_consign_batch_expiry_date_mixing,
    isNotConsignSupplierMixing:
      proxy.$store.state.permission.systemConfig.is_not_consign_supplier_mixing,
    status: 1,
    ...props.params,
  },

  fieldList: [
    {
      label: '仓库名称',
      value: 'depotName',
      disabled: true,
      type: 'input',
    },
    {
      label: '仓库编码',
      value: 'depotCode',
      type: 'input',
      disabled: true,
    },
    {
      label: '状态',
      value: 'status',
      type: 'radio-model',
      code: 'enabled_type',
    },
    {
      label: '货架编号',
      value: 'shelfNumber',
      type: 'input',
      disabled: true,
    },
    {
      label: '货架序号',
      value: 'shelfSerialNo',
      type: 'input',
      disabled: true,
    },
    {
      label: '货位所在列数',
      value: 'locationLine',
      type: 'number',
      disabled: props.modifyType === '1' && !!props.orderId,
      show: props.modifyType === '1' || props.modifyType === '3',
      min: 1,
    },
    {
      label: '货位所在层数',
      value: 'locationLayer',
      type: 'number',
      disabled: props.modifyType === '1' && !!props.orderId,
      show: props.modifyType === '1' || props.modifyType === '3',
      min: 1,
    },
    {
      label: '货位总列数',
      value: 'locationLines',
      type: 'number',
      show: props.modifyType === '2',
      min: 1,
    },
    {
      label: '货位总层数',
      value: 'locationLayers',
      type: 'number',
      show: props.modifyType === '2',
      min: 1,
    },
    {
      label: '货位属性',
      value: 'locationType',
      type: 'select-model',
      code: 'goods_location_type',
      disabled: props.modifyType === '1' && !!props.orderId,
    },
    {
      label: '货位长度(cm)',
      value: 'locationLength',
      type: 'number',
      precision: 2,
      min: 1,
    },
    {
      label: '货位宽度(cm)',
      value: 'locationWidth',
      precision: 2,
      type: 'number',
      min: 1,
    },
    {
      label: '货位高度(cm)',
      value: 'locationHeight',
      precision: 2,
      type: 'number',
      min: 1,
    },
    {
      label: '备注',
      value: 'remark',
      type: 'textarea',
      max: 200,
    },
  ],
  ruleFieldList: [
    {
      label: '寄售产品允许混放',
      value: 'isConsignProductMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '寄售同产品不同批号效期允许混放',
      value: 'isConsignBatchExpiryDateMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '寄售同产品不同供应商允许混放',
      value: 'isConsignSupplierMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售产品允许混放',
      value: 'isNotConsignProductMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售同产品不同批号效期允许混放',
      value: 'isNotConsignBatchExpiryDateMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
    {
      label: '非寄售同产品不同供应商允许混放',
      value: 'isNotConsignSupplierMixing',
      type: 'select-model',
      code: 'yes_or_no',
      checkDefault: false,
    },
  ],
  rules: {
    depotName: [{ required: true, message: '请选择仓库', trigger: 'blur' }],
    locationLayer: [
      { required: true, message: '请输入货位层数', trigger: 'blur' },
    ],
    locationLine: [
      { required: true, message: '请输入货位列数', trigger: 'blur' },
    ],
    locationLayers: [
      { required: true, message: '请输入货位总层数', trigger: 'blur' },
    ],
    locationLines: [
      { required: true, message: '请输入货位总列数', trigger: 'blur' },
    ],
    shelfSerialNo: [
      { required: true, message: '请输入货架序号', trigger: 'blur' },
    ],
  },
  labelWidth: '140px',
})
const fullInfo = ref({
  btnList: [
    { label: '保存', event: save, show: true },
    {
      label: '保存并新增',
      event: saveAdd,
      show: !props.orderId && props.modifyType === '1',
    },
  ],
})
//选择产品相关
const productInfo = ref({
  visible: false,
  query: {
    idNotIn: '',
  },
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canRemoveProduct = computed(() => {
  return tableInfo.value.selections.length
})
watch(
  () => formInfo.value.data.isConsignProductMixing,
  (val) => {
    //启用下的货位修改不允许修改主信息
    if (val == 1) {
      formInfo.value.data.isConsignBatchExpiryDateMixing = '-2'
      formInfo.value.data.isConsignSupplierMixing = '-2'
      showRuleFieldListListItem(false, 'isConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(false, 'isConsignSupplierMixing')
    } else {
      if (formInfo.value.data.isConsignBatchExpiryDateMixing === '-2') {
        formInfo.value.data.isConsignBatchExpiryDateMixing = '0'
      }
      if (formInfo.value.data.isConsignSupplierMixing === '-2') {
        formInfo.value.data.isConsignSupplierMixing = '0'
      }
      showRuleFieldListListItem(true, 'isConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(true, 'isConsignSupplierMixing')
    }
  },
  {
    immediate: true,
    deep: true,
  }
)
watch(
  () => formInfo.value.data.isNotConsignProductMixing,
  (val) => {
    //启用下的货位修改不允许修改主信息
    if (val == 1) {
      formInfo.value.data.isNotConsignBatchExpiryDateMixing = '-2'
      formInfo.value.data.isNotConsignSupplierMixing = '-2'
      showRuleFieldListListItem(false, 'isNotConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(false, 'isNotConsignSupplierMixing')
    } else {
      if (formInfo.value.data.isNotConsignBatchExpiryDateMixing === '-2') {
        formInfo.value.data.isNotConsignBatchExpiryDateMixing = '0'
      }
      if (formInfo.value.data.isNotConsignSupplierMixing === '-2') {
        formInfo.value.data.isNotConsignSupplierMixing = '0'
      }
      showRuleFieldListListItem(true, 'isNotConsignBatchExpiryDateMixing')
      showRuleFieldListListItem(true, 'isNotConsignSupplierMixing')
    }
  },
  {
    immediate: true,
    deep: true,
  }
)

onMounted(() => {
  if (props.orderId) {
    getList()
    getMain()
  }
})

// 获取列表
function getList() {
  tableInfo.value.api = getGoodsLocationProductRelation
  tableInfo.value.refresh = Math.random()
}
// 搜索
function getMain() {
  getGoodsLocationById(props.orderId).then((resp) => {
    if (resp && resp.success) {
      formInfo.value.data = resp.data
      if (props.modifyType === '3') {
        formInfo.value.data.locationLayer = ''
        formInfo.value.data.locationLine = ''
        formInfo.value.data.id = ''
      }
    }
  })
}
function removeProduct(row) {
  let _tableInfo = tableInfo.value
  if (row && row.productId) {
    _tableInfo.data = _tableInfo.data.filter((item) => item !== row)
  } else {
    tableInfo.value.data = tableInfo.value.data.filter((item) => {
      return !_tableInfo.selections.includes(item)
    })
  }
}
function showRuleFieldListListItem(show, nameValue) {
  formInfo.value.ruleFieldList.forEach((item) => {
    if (nameValue === item.value) {
      item.show = show
    }
  })
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.value.selections = [...data]
      break
  }
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let data = {
        wmsGoodsLocationVO: formInfo.value.data,
        wmsGoodsLocationProductRelationVOList: tableInfo.value.data.map(
          (item) => {
            return {
              goodsLocationId: props.orderId,
              capacity: item.capacity,
              productId: item.productId,
            }
          }
        ),
      }
      let api = undefined
      if (props.modifyType === '1') {
        //正常
        api = props.orderId ? updateGoodsLocation : creatGoodsLocation
      } else if (props.modifyType === '2') {
        //快捷
        api = quickCreateGoodsLocation
      } else if (props.modifyType === '3') {
        //复制
        api = creatGoodsLocation
      }
      api(data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false
          emits('returnModify', false)
        }
      })
    }
  })
}
//新增并保存
function saveAdd() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let data = {
        wmsGoodsLocationVO: formInfo.value.data,
        wmsGoodsLocationProductRelationVOList: tableInfo.value.data.map(
          (item) => {
            return {
              goodsLocationId: props.orderId,
              capacity: item.capacity,
              productId: item.productId,
            }
          }
        ),
      }
      creatGoodsLocation(data).then((resp) => {
        if (resp && resp.success) {
          formInfo.value.data.locationLayer = ''
          formInfo.value.data.locationLine = ''
          emits('returnModify', false)
        }
      })
    }
  })
}
function addProduct() {
  productInfo.value.query.idNotIn = tableInfo.value.data
    .map(function (item) {
      return item.productId
    })
    .toString()
  productInfo.value.visible = true
}
function _selectProduct(rows) {
  if (rows) {
    let newData = []
    rows.map((item) => {
      newData.push({
        ...item,
        id: null,
        productId: item.id,
        productCode: item.code,
        productType: item.type,
        capacity: 0,
      })
    })
    tableInfo.value.data.push(...newData)
  }
}
</script>

<style scoped lang="scss">
:deep(.page-table) > .el-table {
  overflow-y: hidden;
}
</style>
